﻿using System;
using System.Collections.Generic;
using TweetSharp.Twitter.Fluent;
using TweetSharp.Twitter.Extensions;
using TweetSharp.Twitter.Model;
using SocialFilter.model;

namespace SocialFilter.controller
{
	class TwitterQuerier : DataSourceQuerier
	{
		private string consumerKey;
		private string consumerSecret;
		
		public TwitterQuerier( string _consumerKey, string _consumerSecret )
		{
			consumerKey = _consumerKey;
			consumerSecret = _consumerSecret;
		}
	
		public override List<SocialFilter.model.FeedItem> RetrieveItems(string _username, string _token)
		{
			if ( !_token.Contains(" ") ) //just return an empty list
			{
				return new List<FeedItem>();
			}
			//split token into token and token secret
			string[] tokenSplit = _token.Split( new char[]{ ' ' } );
			return ParseTwitterStatuses( GetHomeTimeLine(tokenSplit[0], tokenSplit[1]) );
		}

		private List<TwitterStatus> GetHomeTimeLine( string _token, string _tokenSecret )
		{
			List<TwitterStatus> statuses = new List<TwitterStatus>();
		
			ITwitterHomeTimeline query = FluentTwitter.CreateRequest()
																	.AuthenticateWith(consumerKey, consumerSecret, _token, _tokenSecret)
																	.Statuses()
																	.OnHomeTimeline()
																	.Take(200);

			TwitterResult response = query.Request();
			IEnumerable<TwitterStatus> results = response.AsStatuses();

			if (results != null)
			{
				statuses.AddRange(results);
			}
			
			return statuses;
		}
		
		private List<FeedItem> ParseTwitterStatuses( List<TwitterStatus> _statuses )
		{
			List<FeedItem> items = new List<FeedItem>();
			
			foreach ( TwitterStatus status in _statuses )
			{
				// parse status into feed item
				string author = status.User.Name;
				string content = status.TextHtml;
				string url = "twitter.com/#!/" + author + "/status/" + status.Id; //e.g. twitter.com/#!/blitowitz/324134141 
				DateTime timestamp = Convert.ToDateTime(status.CreatedDate);
				items.Add(new FeedItem(content, "twitter", author, timestamp, url));
			}
			
			return items;
		}
	}
}
